package edu.suda.cxtz.service.impl;

import com.github.dozermapper.core.Mapper;
import edu.suda.cxtz.entity.Role;
import edu.suda.cxtz.entity.User;
import edu.suda.cxtz.entity.Menu;
import edu.suda.cxtz.entity.dto.RoleDto;
import edu.suda.cxtz.entity.dto.RoleQueryCriteria;
import edu.suda.cxtz.entity.dto.RoleSmallDto;
import edu.suda.cxtz.entity.dto.UserDto;
import edu.suda.cxtz.modules.security.service.dto.AuthorityDto;
import edu.suda.cxtz.repository.RoleRepository;
import edu.suda.cxtz.repository.UserRepository;
import edu.suda.cxtz.service.RoleService;
import edu.suda.cxtz.utils.*;
import edu.suda.cxtz.modules.exception.BadRequestException;
import edu.suda.cxtz.modules.exception.EntityExistException;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class RoleServiceImpl implements RoleService {

    private final RoleRepository roleRepository;
    private final UserRepository userRepository;
    private final DtoEntityUtil mapper;

    @Override
    public List<RoleDto> queryAll() {
        Sort sort = Sort.by(Sort.Direction.ASC, "level");
        List<Role> roles = roleRepository.findAll(sort);
        return mapper.trans(roles, RoleDto.class);
    }

    @Override
    public PageResult<RoleDto> queryAll(RoleQueryCriteria criteria, Pageable pageable) {
        Page<Role> rolePage = roleRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        List<RoleDto> pageResult = mapper.trans(rolePage, RoleDto.class);
        return PageUtil.toPage(pageResult, rolePage.getTotalElements());
    }

    @Override
    public List<RoleDto> queryAll(RoleQueryCriteria criteria) {
        List<Role> roles = (roleRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        return mapper.trans(roles, RoleDto.class);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RoleDto findById(long id) {
        Role role = roleRepository.findById(id).orElseGet(Role::new);
        ValidationUtil.isNull(role.getId(), "Role", "id", id);
        return mapper.trans(role, RoleDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Role resources) {
        if (roleRepository.findByName(resources.getName()) != null) {
            throw new EntityExistException(Role.class, "username", resources.getName());
        }
        roleRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Role resources) {
        Role role = roleRepository.findById(resources.getId()).orElseGet(Role::new);
        ValidationUtil.isNull(role.getId(), "Role", "id", resources.getId());

        Role role1 = roleRepository.findByName(resources.getName());

        if (role1 != null && !role1.getId().equals(role.getId())) {
            throw new EntityExistException(Role.class, "username", resources.getName());
        }
        role.setName(resources.getName());
        role.setDescription(resources.getDescription());
        role.setDataScope(resources.getDataScope());
        role.setDepts(resources.getDepts());
        role.setLevel(resources.getLevel());
        roleRepository.save(role);
    }

    @Override
    public void updateMenu(Role resources) {
        Role role = roleRepository.findById(resources.getId()).orElseGet(Role::new);
        List<User> users = userRepository.findByRoleId(role.getId());
        // 更新菜单
        role.setMenus(resources.getMenus());
        roleRepository.save(role);
    }

    @Override
    public void addMenu(Long roleId, Menu menu) {
        Role role = roleRepository.findById(roleId).orElseGet(Role::new);
        Set<Menu> menus = role.getMenus();
        menus.add(menu);
        role.setMenus(menus);
        updateMenu(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void untiedMenu(Long menuId) {
        // 更新菜单
        roleRepository.untiedMenu(menuId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        roleRepository.deleteAllByIdIn(ids);
    }

    @Override
    public List<RoleSmallDto> findByUsersId(Long id) {
        Set<Role> roles = roleRepository.findByUserId(id);
        return mapper.trans(roles, RoleSmallDto.class);
    }

    @Override
    public Integer findByRoles(Set<Role> roles) {
        if (roles.isEmpty()) {
            return Integer.MAX_VALUE;
        }
        Set<RoleDto> roleDtos = new HashSet<>();
        for (Role role : roles) {
            roleDtos.add(findById(role.getId()));
        }
        return Collections.min(roleDtos.stream().map(RoleDto::getLevel).toList());
    }

    @Override
    public List<AuthorityDto> mapToGrantedAuthorities(UserDto user) {
        Set<String> permissions = new HashSet<>();
        // 如果是管理员直接返回
        if (user.getIsAdmin()) {
            permissions.add("admin");
            return permissions.stream().map(AuthorityDto::new)
                    .collect(Collectors.toList());
        }
        Set<Role> roles = roleRepository.findByUserId(user.getId());
        permissions = roles.stream().flatMap(role -> role.getMenus().stream())
                .map(Menu::getPermission)
                .filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        return permissions.stream().map(AuthorityDto::new)
                .collect(Collectors.toList());
    }


    @Override
    public void verification(Set<Long> ids) {
        if (userRepository.countByRoles(ids) > 0) {
            throw new BadRequestException("所选角色存在用户关联，请解除关联再试！");
        }
    }

    @Override
    public List<Role> findInMenuId(List<Long> menuIds) {
        return roleRepository.findInMenuId(menuIds);
    }
}
